
package cn.gzjp.common.utils.pay;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * <p>

 */
public final class XmlUtils {
	/**
	 * 日志
	 */
	private static Logger LOG = LoggerFactory.getLogger(XmlUtils.class);

	private XmlUtils() {
		throw new RuntimeException("can't init");
	}

	/**
	 * 作用：array转xml
	 * 
	 * @param map
	 * @return
	 */
	public static String mapToXml(Map<String, String> map) {
		StringBuilder xml = new StringBuilder();
		xml.append("<xml>");
		String value = null;
		for (String key : map.keySet()) {
			value = map.get(key);
			xml.append("<").append(key).append(">");
			if (StringUtils.isNumeric(value)) {
				xml.append(value);
			} else {
				xml.append("<![CDATA[").append(value).append("]]>");
			}
			xml.append("</").append(key).append(">");
		}
		xml.append("</xml>");
		return xml.toString();
	}

	/**
	 * 作用：将xml转为map
	 * 
	 * @param xml
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, String> xmlToMap(String xml) {
		Map<String, String> map = new HashMap<String, String>();
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(xml);
		} catch (DocumentException e) {
			LOG.error(e.getMessage(), e);
		}
		if (null == doc)
			return map;
		Element root = doc.getRootElement();
		for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
			Element e = (Element) iterator.next();
			map.put(e.getName(), e.getText());
		}
		return map;
	}
}
